package com.zxc.config.web;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/*
 * @Author: zxc of Russell
 * @Date: 2021/8/9 9:37
 * @Version 1.0
 * 开启MVC。自动注入spring容器，WebMvcConfigurationAdapter：配置视图解析器
 * 当一个类实现了这个接口（ApplicationContextAware）之后，这个类可以获得applicationContext
 */
@Configuration
@EnableWebMvc //等价于<mvc:annotation-driver  WebMvcConfigurerAdapter注意这里 WebMvcConfigurationSupport
public class MvcConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    //spring容器
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /*
    * 静态资源配置
    * */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/","classpath:META-INF/resources/**");
        super.addResourceHandlers(registry);
    }

    /*
     * 定义默认请求处理器
     * */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    /*
    * 创建视图解析器
    * */
    @Bean(name = "viewResolver ")
    public ViewResolver createViewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        //设置spring容器
        viewResolver.setApplicationContext(applicationContext);
        //取消缓存
        viewResolver.setCache(false);
        //设置解析前缀
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

}
